package com.gamemost.templestay;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.media.MediaPlayer;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.gamemost.dao.BookDatasource;
import com.gamemost.entity.Bookmark;
import com.gamemost.entity.DownloadedBook;
import com.gamemost.layout.LayoutViewReadBook;
import com.gamemost.libepub.Item;
import com.gamemost.managers.ResourcesManager;

@SuppressLint("NewApi")
public class HTML5WebView extends WebView {
	private int pIndex = 0;
	private int sIndex = 0;
	private String clickBk = "";

	public String getClickBk() {
		return clickBk;
	}

	public void setClickBk(String clickBk) {
		this.clickBk = clickBk;
	}

	public int getpIndex() {
		return pIndex;
	}

	public void setpIndex(int pIndex) {
		this.pIndex = pIndex;
	}

	public int getsIndex() {
		return sIndex;
	}

	public void setsIndex(int sIndex) {
		this.sIndex = sIndex;
	}

	private Context mContext;
	private MyWebChromeClient mWebChromeClient;
	private View mCustomView;
	private FrameLayout mCustomViewContainer;
	private WebChromeClient.CustomViewCallback mCustomViewCallback;

	private FrameLayout mContentView;
	private RelativeLayout mBrowserFrameLayout;
	private FrameLayout mLayout;

	static final String LOGTAG = "HTML5WebView";
	GestureDetector gd;
	MediaPlayer globalMediaPlayer;
	boolean jump = false;
	String sJump;

	private void init(Context context) {
		mContext = context;
		Activity a = (Activity) mContext;

		mLayout = new FrameLayout(context);

		mBrowserFrameLayout = (RelativeLayout) LayoutInflater.from(a).inflate(
				R.layout.custom_screen, null);
		mContentView = (FrameLayout) mBrowserFrameLayout
				.findViewById(R.id.main_content);
		mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
				.findViewById(R.id.fullscreen_custom_content);
		mWebChromeClient = new MyWebChromeClient();
		setWebChromeClient(mWebChromeClient);
		setWebViewClient(new MyWebViewClient());
		WebSettings s = getSettings();
		//
		// s.setJavaScriptEnabled(true);
		s.setUseWideViewPort(true);
		s.setLoadWithOverviewMode(true);
		// setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		// setScrollbarFadingEnabled(false);
		// setVerticalScrollBarEnabled(false);
		// setHorizontalScrollBarEnabled(false);
		// getSettings().setPluginsEnabled(true);
		// s.setGeolocationEnabled(true);
		// s.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");
		// s.setDomStorageEnabled(true);
		s.setUseWideViewPort(true);
		s.setLoadWithOverviewMode(true);
		s.setJavaScriptEnabled(true);
		s.setSupportZoom(false);
		s.setBuiltInZoomControls(false);
		s.setDatabaseEnabled(true);

		s.setDomStorageEnabled(true);
		s.setDatabasePath("/data/data/" + this.mContext.getPackageName()
				+ "/app_databases/");
		s.setJavaScriptCanOpenWindowsAutomatically(true);

		s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		s.setSavePassword(true);
		s.setSaveFormData(true);
		s.setJavaScriptEnabled(true);
		//
		s.setTextZoom(100);
		s.setGeolocationEnabled(true);
		addJavascriptInterface(new JavaScriptInterface(), "Android");
		setOnLongClickListener(new View.OnLongClickListener() {

			public boolean onLongClick(View v) {
				return true;
			}
		});
		// addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
		mContentView.addView(this);
	}

	public HTML5WebView(Context context) {
		super(context);
		setLayoutParams(COVER_SCREEN_PARAMS);
		gd = new GestureDetector(context, sogl);
		init(context);
	}

	public HTML5WebView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public HTML5WebView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public RelativeLayout getLayout() {
		return mBrowserFrameLayout;
	}

	public boolean inCustomView() {
		return (mCustomView != null);
	}

	public void hideCustomView() {
		mWebChromeClient.onHideCustomView();
	}

	public class MyWebChromeClient extends WebChromeClient {
		private Bitmap mDefaultVideoPoster;
		private View mVideoProgressView;

		@Override
		public void onShowCustomView(View view,
				WebChromeClient.CustomViewCallback callback) {
			HTML5WebView.this.setVisibility(View.GONE);
			if (mCustomView != null) {
				callback.onCustomViewHidden();
				return;
			}
			LayoutViewReadBook.getInstance().backToScreen = false;
			System.out.println("===onShowCustomview "+LayoutViewReadBook.getInstance().backToScreen);
//			Toast.makeText(ResourcesManager.ac, "onShowCustomview "+LayoutViewReadBook.getInstance().backToScreen, Toast.LENGTH_LONG).show();
			mCustomViewContainer.addView(view);
			mCustomView = view;
			mCustomViewCallback = callback;
			mCustomViewContainer.setVisibility(View.VISIBLE);
		}
		
		@Override
		public void onHideCustomView() {

			if (mCustomView == null)
				return;
			mCustomView.setVisibility(View.GONE);
			mCustomViewContainer.removeView(mCustomView);
			mCustomView = null; 
			mCustomViewContainer.setVisibility(View.GONE);
			mCustomViewCallback.onCustomViewHidden();
			HTML5WebView.this.setVisibility(View.VISIBLE);
			System.out.println("===hideCustomview");
			LayoutViewReadBook.getInstance().backToScreen = false;
			LayoutViewReadBook.getInstance().onKeyBack();
		}

		@Override
		public Bitmap getDefaultVideoPoster() {
			if (mDefaultVideoPoster == null) {
				mDefaultVideoPoster = BitmapFactory.decodeResource(
						getResources(), R.drawable.default_video_poster);
			}
			return mDefaultVideoPoster;
		}

		@Override
		public View getVideoLoadingProgressView() {
			if (mVideoProgressView == null) {
				LayoutInflater inflater = LayoutInflater.from(mContext);
				mVideoProgressView = inflater.inflate(
						R.layout.video_loading_progress, null);
			}
			return mVideoProgressView;
		}

		@Override
		public void onReceivedTitle(WebView view, String title) {
			((Activity) mContext).setTitle(title);
		}

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			((Activity) mContext).getWindow().setFeatureInt(
					Window.FEATURE_PROGRESS, newProgress * 100);
		}

		@Override
		public void onGeolocationPermissionsShowPrompt(String origin,
				GeolocationPermissions.Callback callback) {
			callback.invoke(origin, true, false);
		}

	}

	public static boolean isFirst = true;

	@Override
	public boolean zoomIn() {
		// TODO Auto-generated method stub
		return super.zoomIn();
	}

	@Override
	public boolean zoomOut() {
		// TODO Auto-generated method stub
		return super.zoomOut();
	}

	boolean isLoad = false;
	public boolean isFin = false;

	public class MyWebViewClient extends WebViewClient {
		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			System.out.println("javain onPageFinished " + url);
			isFin = false;
			super.onPageFinished(view, url);
			curUrl = url;
			isLoad = true;

			if (LayoutViewReadBook.settingChange) {
				System.out.println("setting onpage");
				LayoutViewReadBook.settingChange = false;
				LayoutViewReadBook.getInstance().goToPage(
						LayoutViewReadBook.currentPage);
				return;
			} else if (LayoutViewReadBook.getInstance().checkFixLayout()) {
				if (isFirst) {
					LayoutViewReadBook.getInstance().goToPage(
							LayoutViewReadBook.currentPage);
					isFirst = false;
					return;
				} else if (LayoutViewReadBook.landscape.x == 0
						|| LayoutViewReadBook.portrait.x == 0) {
					System.out.println("onpagefin check start");
					LayoutViewReadBook.widthWV = getWidth();
					LayoutViewReadBook.heightWV = getHeight();
					if (LayoutViewReadBook.widthWV > LayoutViewReadBook.heightWV) {
						if (LayoutViewReadBook.landscape.x == 0) {
							System.out.println("onpagefin check land 1");

							LayoutViewReadBook.landscape.x = LayoutViewReadBook.widthWV;
							LayoutViewReadBook.landscape.y = LayoutViewReadBook.heightWV;
							LayoutViewReadBook.getInstance().goToPage(

							LayoutViewReadBook.currentPage);
							return;
						} else if (LayoutViewReadBook.portrait.x == 0
								&& Configuration.ORIENTATION_PORTRAIT == LayoutViewReadBook.orientation) {
							System.out.println("onpagefin check land 2");
							loadDataWithBaseURL("", "", "text/html", "utf-8",
									null);
							return;
						}
					} else if (LayoutViewReadBook.widthWV < LayoutViewReadBook.heightWV) {
						System.out.println("reload onpagefin set portrait "
								+ LayoutViewReadBook.widthWV + " "
								+ LayoutViewReadBook.heightWV);
						if (LayoutViewReadBook.portrait.x == 0) {
							LayoutViewReadBook.portrait.x = LayoutViewReadBook.widthWV;
							LayoutViewReadBook.portrait.y = LayoutViewReadBook.heightWV;
							LayoutViewReadBook.getInstance().goToPage(
									LayoutViewReadBook.currentPage);
							return;
						} else if (LayoutViewReadBook.landscape.x == 0
								&& Configuration.ORIENTATION_LANDSCAPE == LayoutViewReadBook.orientation) {
							loadDataWithBaseURL("", "", "text/html", "utf-8",
									null);
							return;
						}
					}
				}
			}
			if (!jump) {
				ResourcesManager.ac.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						ResourcesManager.ac.waitDialog.hide();
					}
				});
			}
			isFin = true;
			System.out.println("onPage====");
			if (LayoutViewReadBook.getInstance().haveAutoVideo) {
				System.out.println("autovideooooooo");
				LayoutViewReadBook.getInstance().haveAutoVideo = false;
				loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
			}
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			url = url.replace(LayoutViewReadBook.base, "");
			System.out.println("shouldOverrideUrlLoading " + url);
			if (url.contains("#")) {
				String[] tmpArr = url.split("#");
				jump = true;
				sJump = tmpArr[1];
				int p = LayoutViewReadBook.getPage(tmpArr[0]);
				LayoutViewReadBook.getInstance().currentPage = p;
				LayoutViewReadBook.getInstance().current_percent = 0;
				System.out.println("pt===chapter" + p);
				// loadUrl(LayoutViewReadBook.base+tmpArr[0]);
				// Thread th = new Thread(new Runnable() {
				//
				// @Override
				// public void run() {
				// // TODO Auto-generated method stub
				// percent = LayoutViewReadBook.getPercentInPage(
				// LayoutViewReadBook.getInstance().dataArr.get(LayoutViewReadBook.currentPage),
				// sJump);
				// }
				// });
				// th.run();
				LayoutViewReadBook.getInstance().loadSinglePage(p);
				ResourcesManager.ac.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						ResourcesManager.ac.waitDialog.show();
					}
				});
				return true;
			} else {
				int p = LayoutViewReadBook.getPage(url);
				if (LayoutViewReadBook.orientation == Configuration.ORIENTATION_LANDSCAPE) {
					if (p - LayoutViewReadBook.currentPage >= 2
							|| p - LayoutViewReadBook.currentPage <= -2) {
						LayoutViewReadBook.jumpPage = p
								- LayoutViewReadBook.currentPage;
					}
				} else {
					if (p - LayoutViewReadBook.currentPage >= 1
							|| p - LayoutViewReadBook.currentPage <= -1) {
						LayoutViewReadBook.jumpPage = p
								- LayoutViewReadBook.currentPage;
					}
				}
			}
			return false;
		}
	}

	public boolean isdownwebview = false;
	static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.FILL_PARENT);
	GestureDetector.SimpleOnGestureListener sogl = new GestureDetector.SimpleOnGestureListener() {
		// your fling code here

		public void onLongPress(MotionEvent e) {
			if (!isdownwebview) {
				LayoutViewReadBook.getInstance().showTap();
				isdownwebview = true;
			} else {
				LayoutViewReadBook.getInstance().hideTap();
				isdownwebview = false;
			}
			return;
		};

	};

	int numLoad = 0;
	public String[] data = new String[2];
	int percent;

	public void init(boolean nextPage) {
		for (int i = 0; i < 2; i++) {
			try {
				numLoad = 0;
				if (nextPage)
					data[i] = LayoutViewReadBook
							.getPageData(LayoutViewReadBook.currentPage + i);
				else
					data[i] = LayoutViewReadBook
							.getPageData(LayoutViewReadBook.currentPage - i);

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void loadPageEpub(int page) {
		if (data[numLoad % 2].contains("<math")) {
			loadDataWithBaseURL("http://bar", data[numLoad % 2], "text/html",
					"UTF-8", null);
		} else {
			loadDataWithBaseURL(LayoutViewReadBook.baseUrl, data[numLoad % 2],
					"text/html", "UTF-8", null);
		}
		if (numLoad % 2 == 0) {
			try {
				data[0] = LayoutViewReadBook.getPageData(page);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				data[1] = LayoutViewReadBook.getPageData(page);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		numLoad = numLoad + 1;
	}

	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	int mode;
	float newDist, oldDist;
	float oldX, oldY, newX, newY;
	float downTime, upTime, moveTime;

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		gd.onTouchEvent(event);
		int action = event.getAction() & MotionEvent.ACTION_MASK, p_count = event
				.getPointerCount();

		switch (action) {
		case MotionEvent.ACTION_DOWN:
			if (mode == 3)
				mode = 0;
			if (LayoutViewReadBook.getInstance().orienChange) {
				if (!LayoutViewReadBook.checkFixLayout())
					loadUrl("javascript:window.Android.getPages(getPages())");
				LayoutViewReadBook.getInstance().orienChange = false;
			}
			oldX = event.getX();
			oldY = event.getY();
			downTime = android.os.SystemClock.uptimeMillis();
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			oldDist = spacing(event);
			if (oldDist > 10f) {
				mode = 1;
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if (p_count > 1) {
				if (mode == 1) {
					newDist = spacing(event);
//					System.out.println("zoom touch move if");
					if (newDist > 10f) {
						float scale = newDist / oldDist;
						if (scale > 1) 
							zoomIn();
						else
							zoomOut();
						System.out.println("getPages onTouch");
						loadUrl("javascript:window.Android.getPages(getPages())");
					}
				}
			} else if (mode == 0) {
				mode = 2;
			}
			break;
		case MotionEvent.ACTION_UP:
			if (mode == 2) {
				upTime = android.os.SystemClock.uptimeMillis();
				moveTime = upTime - downTime;
				newX = event.getX();
				newY = event.getY();
				System.out.println("newX = "+newX+", oldX= "+oldX);
//				float distance = (float) Math.sqrt((newX - oldX)
//						* (newX - oldX) + (newY - oldY) * (newY - oldY));
				float distance = Math.abs(newX - oldX);
				float speed = distance / moveTime;
				if (newX - oldX < 0 && distance > SWIPE_MIN_DISTANCE
						&& speed > 0.8) {

					LayoutViewReadBook.getInstance().nextPage();
				} else if (newX - oldX > 0 && distance > SWIPE_MIN_DISTANCE
						&& speed > 0.8) {
					LayoutViewReadBook.getInstance().prevPage();
				}				

			} else if (mode == 1)
				mode = 3;

			break;
		default:
			break;
		}
		return super.onTouchEvent(event);
	}

	public void changeFontSize(int value) {
		getSettings().setDefaultFontSize(value);
	}

	public void captureBookmark(String filename, boolean split, boolean left) {
		Picture picture = capturePicture();
		Bitmap bitmap, bmp;
		bitmap = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(),
				Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		draw(canvas);
		picture.draw(canvas);
		if (split) {
			if (left)
				bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth() / 2,
						bitmap.getHeight());
			else
				bmp = Bitmap.createBitmap(bitmap, bitmap.getWidth() / 2, 0,
						bitmap.getWidth() / 2, bitmap.getHeight());
		} else
			bmp = bitmap;
		FileOutputStream fos = null;

		try {
			fos = new FileOutputStream(Environment
					.getExternalStorageDirectory().getPath()
					+ Config.IMAGE_BOOKMARK + "/" + filename);
			System.out.println("pppppppppppp "
					+ Environment.getExternalStorageDirectory().getPath()
					+ Config.IMAGE_BOOKMARK + "/" + filename);
			if (fos != null) {
				bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
				fos.close();
			}

		} catch (Exception e) {
		}
	}

	public static boolean haveBm;
	private boolean flinged;
	private static final int SWIPE_MIN_DISTANCE = 50;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 100;
	String pathAudio = "";
	boolean firstPlay = false;
	boolean justFromBm = false;
	int oldCurrentPage = 0;

	public class JavaScriptInterface {
		public JavaScriptInterface() {
		}

		@JavascriptInterface
		public void currentReadingData(int num, int pages) {
			System.out.println(num + "," + pages + "javain current_percent==="
					+ LayoutViewReadBook.current_percent);
			if (justFromBm) {
				LayoutViewReadBook.curPageInchap = num;
				LayoutViewReadBook.current_percent = (LayoutViewReadBook.curPageInchap * 10000 / pages);
				if (LayoutViewReadBook.currentPage == oldCurrentPage)
				LayoutViewReadBook.getInstance().loadSinglePage(oldCurrentPage);
				justFromBm = false;
			} else {
				if (pages == 1) LayoutViewReadBook.curPageInchap = num;
				else LayoutViewReadBook.curPageInchap  = num - 1;
				LayoutViewReadBook.current_percent = (num * 10000 / pages);
			}
			if (LayoutViewReadBook.getInstance().isShowToolbar) {
				System.out.println("reflowBookmark:currentReadin");
				loadUrl("javascript:window.Android.checkBookmark(checkBookmark())");
			}
			if (LayoutViewReadBook.currentPage == LayoutViewReadBook
					.getInstance().tableContent.size() - 1) {
				int afterread = LayoutViewReadBook.getInstance().getReadePage(
						LayoutViewReadBook.currentPage - 1);
				int charread = LayoutViewReadBook.current_percent
						* (LayoutViewReadBook.getItemPage(
								LayoutViewReadBook.currentPage).getNumChar() / 10000);
				LayoutViewReadBook.getInstance().percent = afterread + charread;
				LayoutViewReadBook.getInstance().changeScrollBar();
			}
			if (num == 1) {
				// go to
			}
			// if (numIndex != -1 && (numIndex - 1) ==
			// LayoutViewReadBook.curPageInchap) {
			// System.out.println("javain change"+LayoutViewReadBook.curPageInchap);
			// numIndex = -1;
			// LayoutViewReadBook.getInstance().loadSinglePage(LayoutViewReadBook.currentPage);
			// }
			// +
			// LayoutViewReadBook.current_percent+","+LayoutViewReadBook.getInstance().isLoad);
			// if (!LayoutViewReadBook.getInstance().isLoad) {
			// LayoutViewReadBook.curPageInchap = num - 1;
			// LayoutViewReadBook.current_percent =
			// (LayoutViewReadBook.curPageInchap * 10000 / pages);
			// LayoutViewReadBook.getInstance().isLoad = false;
			// System.out.println(num + "," + pages +
			// "javain current_percent==="
			// +
			// LayoutViewReadBook.current_percent+","+LayoutViewReadBook.getInstance().isLoad);
			// }
		}

		@JavascriptInterface
		public void checkBookmark(int bm) {
			boolean checkFromclick = LayoutViewReadBook.getInstance().checkBmFromClick;
			System.out.println("android checkBookmark " + bm + " "
					+ checkFromclick);
			if (bm == 0) {
				// dont bookmark
				if (checkFromclick) {
					System.out.println("dont have bookmark");
					if (LayoutViewReadBook.getInstance().imgBookmark) {
						// sysout delete bookmark
						System.out.println("reflowBookmark delBoomark");
					} else {
						ResourcesManager.ac.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								// loadUrl("javascript:window.Android.addBookmark()");
								LayoutViewReadBook.getInstance()
										.setBookmarkedIcon();
								loadUrl("javascript:addBookmark()");
							}
						});
					}
					LayoutViewReadBook.getInstance().checkBmFromClick = false;
				} else {
					System.out.println("dont have bookmark and dont show");					
					LayoutViewReadBook.getInstance().setNoBookmarkIcon();
				}
			} else if (bm > 0) {
				// bookmark
				if (checkFromclick) {
					System.out.println("have bookmark and delete");				
					LayoutViewReadBook.getInstance().checkBmFromClick = false;
					// LayoutViewReadBook.current_percent += 1;
					// LayoutViewReadBook.getInstance().loadSinglePage(LayoutViewReadBook.currentPage);
					ResourcesManager.ac.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							loadUrl("javascript:delBookmark()");
					
						}
					});
				} else {
					System.out.println("have bookmark and show");
					LayoutViewReadBook.getInstance().setBookmarkedIcon();
				}
			}
		}

		// public boolean isBookmark(int bm) {
		// if (bm == 0) {
		// return false;
		// }
		// else if (bm == 1) return true;
		// return false;
		// }
		@JavascriptInterface
		public void addBookmark(int bmState) {
			System.out.println("addBookmark android");

		}
		@JavascriptInterface
		public void delBookmark(int deleteBKIndex) {
			System.out.println(LayoutViewReadBook.current_percent+" delBookmark android  " + 10000 / LayoutViewReadBook.getItemPage(LayoutViewReadBook.currentPage).getNumPages());
			LayoutViewReadBook
			.getInstance()
			.getCurrentBookReading()
			.delBookmarkReflow(LayoutViewReadBook.currentPage,
					deleteBKIndex);
//			LayoutViewReadBook.current_percent += 10000 / LayoutViewReadBook.getItemPage(LayoutViewReadBook.currentPage).getNumPages();
//			if (LayoutViewReadBook.current_percent>=1000) LayoutViewReadBook.current_percent = 10000; 
			 LayoutViewReadBook.getInstance().loadSinglePage(LayoutViewReadBook.currentPage);
		}

		String bmOfChap;

		@JavascriptInterface
		public void storeData(String bmData) {
			System.out.println(bmData.length() + " bookmark reflow storeData");
			String[] dataArr = bmData.split("afd_item");
			System.out.println(" bookmark reflow storeData array "
					+ dataArr.length);
			String spanCon = "";
			String sText = "";
			if (Integer.parseInt(dataArr[1]) == -1) {
				sText = "....";

			} else {
				sText = dataArr[3];
			}
			spanCon = dataArr[4].replace("\n", "");
			Bookmark bm = new Bookmark(Integer.parseInt(dataArr[0]),
					Integer.parseInt(dataArr[1]), Integer.parseInt(dataArr[2]),
					sText);
			System.out.println(" bookmark reflow storeData array 3 " + sText);
			System.out.println(" bookmark reflow storeData array 4 " + spanCon);

			DownloadedBook book = LayoutViewReadBook.getInstance()
					.getCurrentBookReading();
			bm.setBookmark(dataArr[0] + "afd_item" + dataArr[1] + "afd_item"
					+ dataArr[2] + "afd_item" + sText + "afd_item" + spanCon);
			book.addBookmarkReflow(bm);
			BookDatasource.getInstance(ResourcesManager.ac.getBaseContext())
					.updateBookmarkReflow(book);
			currentReadingData(LayoutViewReadBook.curPageInchap+1, LayoutViewReadBook.getItemPage(LayoutViewReadBook.currentPage).getNumPages());
//			System.out.println(LayoutViewReadBook.current_percent+" delBookmark android  " + 10000 / LayoutViewReadBook.getItemPage(LayoutViewReadBook.currentPage).getNumPages());
//			LayoutViewReadBook.current_percent += 10000 / LayoutViewReadBook.getItemPage(LayoutViewReadBook.currentPage).getNumPages();
//			 LayoutViewReadBook.getInstance().loadSinglePage(LayoutViewReadBook.currentPage);			
		}

		@JavascriptInterface
		public void resizePage() {
			// BookView.this.afd_webView.loadUrl("javascript:getAndroidVersion("
			// +
			// BookView.this.androidVersion + ");");
			ResourcesManager.ac.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					LayoutViewReadBook.getInstance().hideTap(); // ensure
																// getBookData
																// is called,
																// before check
																// bookmark.
				}
			});
			DownloadedBook book = LayoutViewReadBook.getInstance()
					.getCurrentBookReading();
			if (!LayoutViewReadBook.getInstance().fromBookmark) {
				// bmOfChap =
				// LayoutViewReadBook.getInstance().getCurrentBookReading().getListBookmarkOfChapter(LayoutViewReadBook.currentPage);
				// System.out.println("bmOfChap= "+bmOfChap);
				// if (bmOfChap.length() < 5) bmOfChap = "undefined";
				System.out.println("resizePage is"
						+ LayoutViewReadBook.getInstance().getPercent()
						+ ","
						+ LayoutViewReadBook
								.getNumCharPage(LayoutViewReadBook.currentPage)
						+ "," + LayoutViewReadBook.allChar + ","
						+ LayoutViewReadBook.currentPage + ","
						+ LayoutViewReadBook.tableContent.size() + ",'"
						+ LayoutViewReadBook.getInstance().getCurrentBookReading().getId() + "','" + "bbbbbb" + "','" + "ccccccccc"
						// + "','" + bmOfChap
						+ ",");
				
				ResourcesManager.ac.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						loadUrl("javascript:getBookData("
								+ LayoutViewReadBook.getInstance().getPercent()
								+ ","
								+ LayoutViewReadBook
										.getNumCharPage(LayoutViewReadBook.currentPage)
								+ "," + LayoutViewReadBook.allChar + ","
								+ LayoutViewReadBook.currentPage + ","
								+ LayoutViewReadBook.tableContent.size() + ",'"
								+ LayoutViewReadBook.getInstance().getCurrentBookReading().getId() + "','" + LayoutViewReadBook.baseUrl + "','"
								+ LayoutViewReadBook.getInstance().getCurrentBookReading().getTitle()
								 + "'," + LayoutViewReadBook.getInstance().getCurrentBookReading().getBmarkArray().size()
								+ ");");
						loadUrl("javascript:window.Android.getPages(getPages())");
						System.out.println(LayoutViewReadBook.getInstance().fromIndexes
								+ " resizePage currentpercent "
								+ LayoutViewReadBook.current_percent);
						loadUrl("javascript:resizePage("
								+ LayoutViewReadBook.current_percent + ","
								+ pIndex + "," + sIndex + ",'" + clickBk
								+ "');");
						clickBk = "";
						pIndex = 0;
						sIndex = 0;
					}
				});

			} else {
				ResourcesManager.ac.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						loadUrl("javascript:window.Android.getPages(getPages())");
						loadUrl("javascript:resizePage("
								+ LayoutViewReadBook.current_percent + ","
								+ pIndex + "," + sIndex + ",'" + clickBk
								+ "');");
					}
				});
				justFromBm = true;
				oldCurrentPage = LayoutViewReadBook.currentPage;
				System.out.println("reflowBookmark resizePage first");
			}

			if (!LayoutViewReadBook.getInstance().loadAfterOrienchange) {
				LayoutViewReadBook.getInstance().loadAfterOrienchange = true;
				LayoutViewReadBook.getInstance().loadSinglePage(
						LayoutViewReadBook.currentPage);
			}
			if (LayoutViewReadBook.getInstance().fromIndexes)
				LayoutViewReadBook.getInstance().fromIndexes = false;

		}

		boolean changeScrollbar = false;

		@JavascriptInterface
		public void getPages(String val) {
			isdownwebview = false;
			// if page is shown by user choose "Go to bookmark".
			Item item = LayoutViewReadBook
					.getItemPage(LayoutViewReadBook.currentPage);
			item.setNumPages(Integer.parseInt(val));
			if (changeScrollbar) {
				changeScrollbar = false;
				// System.out.println(" pt===changscrollbar "
				// + LayoutViewReadBook.getInstance().data[0].length()
				// + "," + ","
				// + LayoutViewReadBook.getInstance().data[1].length());
				int afterread = LayoutViewReadBook.getInstance().getReadePage(
						LayoutViewReadBook.currentPage - 1);
				int charread = LayoutViewReadBook.current_percent
						* (LayoutViewReadBook.getItemPage(
								LayoutViewReadBook.currentPage).getNumChar() / 10000);
				LayoutViewReadBook.getInstance().percent = afterread + charread;
				System.out.println("pt===="
						+ LayoutViewReadBook.getInstance().percent
						+ ","
						+ LayoutViewReadBook.getItemPage(
								LayoutViewReadBook.currentPage).getNumChar()
						+ "," + LayoutViewReadBook.current_percent);
				LayoutViewReadBook.getInstance().changeScrollBar();
				ResourcesManager.ac.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						ResourcesManager.ac.waitDialog.hide();
					}
				});
			} else if (!jump) {
				ResourcesManager.ac.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						ResourcesManager.ac.waitDialog.hide();
					}
				});
			}
			if (jump) {
				changeScrollbar = true;
				jump = false;
				System.out.println("pt===jump");
				percent = LayoutViewReadBook.getPercentInPage(
						LayoutViewReadBook.getInstance().dataArr
								.get(LayoutViewReadBook.currentPage), sJump);
				System.out.println("pt===jump " + percent);

				float tmpCur = ((float) (percent * Integer.parseInt(val)) / (float) 10000);
				LayoutViewReadBook.curPageInchap = Math.round(tmpCur + 1);
				System.out.println("pt===jump " + percent + ", "
						+ LayoutViewReadBook.curPageInchap);

				LayoutViewReadBook.current_percent = LayoutViewReadBook.curPageInchap
						* 10000 / Integer.parseInt(val);
				resizePage();
				System.out.println(percent + ","
						+ LayoutViewReadBook.current_percent + " pt==="
						+ LayoutViewReadBook.curPageInchap);

			} else if (LayoutViewReadBook.getInstance().fromBookmark) {
				// LayoutViewReadBook.getInstance().updateUIBookmark();
				LayoutViewReadBook.getInstance().fromBookmark = false;
				System.out.println(LayoutViewReadBook.currentPage
						+ " reflowBookmark getPages " + item.getNumPages());
				ResourcesManager.ac.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						LayoutViewReadBook.getInstance().loadSinglePage(
								LayoutViewReadBook.currentPage);
					}
				});
			} else {
				System.out.println("getPages normal "+item.getNumPages());
				if (item.getNumPages() != 1) {
				LayoutViewReadBook.getInstance().curPageInchap = (int) Math
						.ceil(LayoutViewReadBook.current_percent
								* Integer.parseInt(val) / 10000);
				} else {
					LayoutViewReadBook.getInstance().curPageInchap = 0;
				}
			}
			System.out.println(LayoutViewReadBook.current_percent + " "
					+ LayoutViewReadBook.getInstance().curPageInchap
					+ " scrolltest nextPage land getPage====== "
					+ LayoutViewReadBook.getInstance().fromBookmark);
		}

	}

	public String curUrl;
}